package com.isoft.illustrationsdraw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isoft.illustrationsdraw.entity.Report;
import com.isoft.illustrationsdraw.entity.ReportStatusLog;
import com.isoft.illustrationsdraw.mapper.ReportMapper;
import com.isoft.illustrationsdraw.service.EmailService;
import com.isoft.illustrationsdraw.service.ReportService;
import com.isoft.illustrationsdraw.service.ReportStatusLogService;
import com.isoft.illustrationsdraw.service.UserService;

import java.util.List;

import org.springframework.stereotype.Service;

@Service
public class ReportServiceImpl extends ServiceImpl<ReportMapper, Report> implements ReportService {

    private final ReportStatusLogService reportStatusLogService;
    private final ReportMapper reportMapper;
    private final EmailService emailService;
    private final UserService userService;

    public ReportServiceImpl(UserService userService, EmailService emailService, ReportMapper reportMapper, ReportStatusLogService reportStatusLogService) {
        this.reportStatusLogService = reportStatusLogService;
        this.userService = userService;
        this.reportMapper = reportMapper;
        this.emailService = emailService;
    }

    @Override
    public boolean creatNewReport(Report report) {
        boolean result = save(report);
        ReportStatusLog newLog = new ReportStatusLog();
        newLog.setReportId(report.getId());
        return result && reportStatusLogService.save(newLog);
    }



    @Override
    public List<Report> getReports(String status) {
        QueryWrapper<Report> queryWrapper = new QueryWrapper<>();
        if (status.equals("all")) {
            return reportMapper.selectList(null);
        } else {
            queryWrapper.eq("status", status);
            return list(queryWrapper);
        }
        
    }
    

    @Override
    public boolean updateReportAndLog(ReportStatusLog reportStatusLog) {
        var report = getById(reportStatusLog.getReportId());
        var reportLog = reportStatusLogService.getLogByReportId(reportStatusLog.getReportId());


        report.setStatus(reportStatusLog.getStatus());
        reportLog.setStatus(reportStatusLog.getStatus());
        emailService.sendReportUpdateRemindToReporter(userService.getById(report.getReporterId()).getEmail(), reportLog);

        // return (result1 && result2);
        return (reportStatusLogService.updateById(reportLog) && updateById(report));
    }
    
}
